import React, { Component } from 'react';
import { Modal, Tabs, Button, Icon } from 'antd';
import FileCenterComp from '/common/componentsTpl/FileCenterComp';
import FileUploadComp from '/common/componentsTpl/FileUploadComp';
import FilePreviewComp from '/common/componentsTpl/FilePreviewComp';
// import classNames from 'classnames';
import styles from './index.less';
import { isEmpty, isFunction, map } from 'lodash';

const TabPane = Tabs.TabPane;

export default class FileUploadModal extends Component {

  constructor(props) {
    super(props);
    this.state = {
      selectRowKeys: [],
      selectRows: [],
      uploadRowKeys: [],
      currentDirId: 0,
      uploadActive: false,
      curPaneKey: 'previews', // 当前显示的 tabPane；"previews": 已关联附件; "file":文件中心 ;"upload":上传新文件;
      curPreviewFiles: [], // 当前“已关联附件”的列表数据
    };
  }

  setCurrentDirId(dirId, page) {

    this.setState({
      currentDirId: dirId,
    });

    if ('upload' == page) {
      if (this.fileRef) {
        this.fileRef.fetchFile &&
        this.fileRef.fetchFile(dirId);
      }
    }
  }


  okModal = () => {
    const { confirmModalCb } = this.props;
    confirmModalCb && confirmModalCb({});
  };

  cancelModal = () => {
    this.props.cancelModalCb &&
    this.props.cancelModalCb();
  };

  /**
   * 批量删除选中的附件
   */
  deleteRecord = () => {

  };

  /**
   * 选择附件
   */
  onSelectFileChange = (selectRowKeys, selectRows) => {
    this.setState({
      selectRowKeys,
      selectRows,
    });
  };

  /**
   * 选中确认
   */
  onSelectFile() {
    const { selectRowKeys, selectRows } = this.state;
    if (selectRowKeys) {
      this.triggerConfirm(selectRowKeys, selectRows);
    }
  }

  //确认选中的文件
  triggerConfirm(changedKey, changedObj) {
    console.log('triggerConfirm', changedObj);
    // 添加到“已关联文件”
    if (this.filePreviewRef && isFunction(this.filePreviewRef.addPreviewFiles)) {
      this.filePreviewRef.addPreviewFiles(map(changedObj, v => ({
        // originId: v.originId || 0,
        name: v.fileName,
        ext: v.ext,
        saveName: v.saveName,
        path: v.savePath,
        size: v.size,
        id: v.id,
      })));
    }

    // 如果有回调，则回调
    const onChange = this.props.onChangeFile;
    if (onChange) {
      onChange(changedKey, changedObj);
    }

    //清空changedKey,changedObj
    this.fileRef &&
    this.fileRef.clearSelectedRow();
    // this.onSelectFileChange([], []);
    // 关闭
    this.hideUpload();
  }

  //预上传文件
  uploadFileRow(uploadRow) {
    this.setState({
      uploadRowKeys: uploadRow,
    });
  }

  /**
   * 上传文件后回调
   */
  handleUpload({ dirId, files }) {
    console.log('handleUpload...:', files);

    if (!isEmpty(files) && this.filePreviewRef && isFunction(this.filePreviewRef.addPreviewFiles)) {
      this.filePreviewRef.addPreviewFiles(files
        .filter(v => (v && v.originFileObj))
        .map(v => ({
          originId: null,
          name: v.name,
          ext: v.ext,
          saveName: v.saveName,
          path: v.savePath,
          size: v.size,
          id: v.id || 0,
        })));

      this.hideUpload();
    }
  }

  /**
   * 文件上传
   */
  fileUploadCb() {
    if (this.fileUploadRef) {
      this.fileUploadRef.handleUpload &&
      this.fileUploadRef.handleUpload();
    }
  }

  hideUpload() {
    this.setState({
      curPaneKey: 'previews',
      selectRowKeys: [],
      uploadRowKeys: [],
    });
  }

  render() {
    const { visible } = this.props,
      hasSelectBtnDis = this.state.selectRowKeys.length > 0,
      hasUploadBtnDis = this.state.uploadRowKeys.length > 0;
    let paneHeight = document.body.offsetHeight - 350;

    const layoutTabs = (
      <Tabs key={this.props.showPaneKey}
            renderTabBar={() => (<div/>)}
            tabBarStyle={{ marginBottom: '0px' }}
            activeKey={this.state.curPaneKey}
      >
        <TabPane tab="已关联附件" key="previews">
          {
            true !== this.props.onlyPreview && (

              <div className={styles.paneBtn} style={{ paddingLeft: 0 }}>
                <Button type="primary" onClick={() => {
                  this.setState({ curPaneKey: 'upload' });
                }}>上传新文件</Button>
                <Button type={'primary'} ghost onClick={() => {
                  const curPreviewFiles = this.filePreviewRef.getPreviewFile();
                  this.setState({ curPaneKey: 'file', curPreviewFiles });
                }}>从文件中心选择</Button>
              </div>
            )
          }
          <div className={styles.fileTabs}>
            <FilePreviewComp
              style={{ height: paneHeight }}
              ref="filePreviewRef"
              onRef={(ref) => {
                this.filePreviewRef = ref;
              }}
              onlyPreview={this.props.onlyPreview}
              compData={this.props.preViewData ? this.props.preViewData : []}
            />
            {
              this.props.onlyPreview === false &&
              <div className={styles.paneBtn} style={{ textAlign: 'center', paddingTop: 16 }}>
                <Button
                  type="primary"
                  onClick={e => {
                    if (this.filePreviewRef) {
                      let list = this.filePreviewRef.getPreviewFile();
                      if (this.props.onChangePreview) {
                        this.props.onChangePreview(list);
                      }
                      this.props.cancelModalCb && this.props.cancelModalCb();
                    }
                  }
                  }>确认</Button>
                <Button onClick={this.cancelModal.bind(this)}>取消</Button>
              </div>
            }
          </div>
        </TabPane>

        {
          (this.props.onlyPreview === false && 'file' === this.state.curPaneKey) &&
          <TabPane tab="从文件中心选择" key="file">
            <div className={styles.paneBtn} style={{ paddingLeft: 0 }}>
              <Button onClick={this.hideUpload.bind(this)}><Icon type="left"/></Button> 从文件中心选择
            </div>
            <div className={styles.fileTabs}>
              <FileCenterComp
                ref="fileCompRef"
                treeHeight={paneHeight}
                fileOper={false}
                onRef={(ref) => {
                  this.fileRef = ref;
                }}
                setCurrentDirId={this.setCurrentDirId.bind(this)}
                curDirId={this.state.dirId}
                curFiles={this.state.curPreviewFiles || []}
                deleteRecord={this.deleteRecord.bind(this)}
                onSelectChange={this.onSelectFileChange.bind(this)}
              />

              {
                this.props.onlyPreview === false &&
                <div className={styles.paneBtn} style={{ textAlign: 'center', paddingTop: 16 }}>
                  <Button type="primary"
                          onClick={this.onSelectFile.bind(this)}
                          disabled={!hasSelectBtnDis}>确认选择</Button>
                  <Button onClick={this.hideUpload.bind(this)}>取消</Button>
                </div>
              }
            </div>
          </TabPane>
        }
        {
          (this.props.onlyPreview === false && 'upload' === this.state.curPaneKey) && (
            <TabPane tab="上传新文件" key="upload">
              <div className={styles.paneBtn} style={{ paddingLeft: 0 }}>
                <Button onClick={this.hideUpload.bind(this)}><Icon type="left"/></Button> 上传新文件
              </div>
              <div className={styles.fileTabs}>
                <FileUploadComp
                  isModal={false}
                  boxHeight={paneHeight}
                  setCurrentDirId={this.setCurrentDirId.bind(this)}
                  curDirId={this.state.dirId}
                  handleUpload={this.handleUpload.bind(this)}
                  uploadFileRowCb={this.uploadFileRow.bind(this)}
                  onRef={(ref) => {
                    this.fileUploadRef = ref;
                  }}/>
                <div className={styles.paneBtn} style={{ textAlign: 'center', paddingTop: 16 }}>
                  <Button type="primary"
                          onClick={this.fileUploadCb.bind(this)}
                          disabled={!hasUploadBtnDis}>确认上传</Button>
                  <Button onClick={this.hideUpload.bind(this)}>取消</Button>
                </div>
              </div>
            </TabPane>
          )
        }
      </Tabs>
    );
    return (
      <>
        <Modal title={this.props.modalTile}
               bodyStyle={{ padding: '8px 24px 0' }}
               keyboard={false}
               maskClosable={false}
               visible={visible}
               onOk={this.okModal.bind(this)}
               destroyOnClose={true}
               onCancel={this.cancelModal.bind(this)}
               footer={null}
               width="70%"
               okText="确认"
               cancelText="取消">
          {layoutTabs}
        </Modal>
      </>
    );
  }

}

FileUploadModal.defaultProps = {
  visible: false,                      //弹框的显示状态
  isCancelVisible: false,            //是否显示取消按钮
  onChangePreview: (changedValue) => {
  }, //预览文件,修改后的回调
  onChangeFile: (changedValue) => {
  }, //选中的文件回调 array,[id1,id2,id3]
  preViewData: [],                      //预览文件
  showPaneKey: 'previews',              //默认显示Tabs, previews 预览;upload文件上传;file 文件中心
  onlyPreview: false,
  modalTile: '附件上传',
};
